"""
以王者荣耀为例

dir：
    url：当前请求的地址
    request.headers：请求头  U-A

content：带有b  未解码的  2进制数节流
json：好展开，直接是数据字典
text：全部内容，带有标签
"""
import time

import requests
# # 1.获取目标url
# url = "https://pvp.qq.com/web201605/js/herolist.json"
# # 2.构造请求
# # 3.获取响应
# res = requests.get(url=url)
# # print(res)  # <Response [200]>
# # print(dir(res))  # ==> text
# # 4.解析提取数据
# res = res.json()
# for data in res:
#     # 头像
#     # https://game.gtimg.cn/images/yxzj/img201606/heroimg/517/517.jpg
#     # print(data["cname"], data["ename"])  # 大司命 517
#     name = data["cname"]
#     head_url = f'https://game.gtimg.cn/images/yxzj/img201606/heroimg/{data["ename"]}/{data["ename"]}.jpg'
#     # print(data["cname"], head_url)
#     # 再次请求图片的url
#     head_res = requests.get(url=head_url)
#     # print(head_res)
#     # print(head_res.content)
#     # 保存图片
#     with open(f"{name}.jpg", "wb") as f:
#         f.write(head_res.content)
#     # 灵活运用break
#     break


class WZSpider:
    def __request(self, url, parser, **kwargs):
        self.res = requests.get(url=url)
        parser(self.res, **kwargs)

    def __parser_head(self, res, **kwargs):
        name = kwargs.get("cname")
        with open(f"王者荣耀_head/{name}.jpg", "wb") as f:
            f.write(res.content)
        print(f"{name}头像爬取成功")

    def __parser(self, res):
        for data in res.json():
            # print(data)
            name = data["cname"]
            head_url = f'https://game.gtimg.cn/images/yxzj/img201606/heroimg/{data["ename"]}/{data["ename"]}.jpg'
            self.__request(head_url, self.__parser_head, cname=name)
            time.sleep(2)

    def start(self, url):
        self.__request(url, self.__parser)


wang_zhe = WZSpider()
wang_zhe.start("https://pvp.qq.com/web201605/js/herolist.json")
